#coding=utf-8
#消息宏定义类型和解析及封包函数


from xml.dom import minidom
import mg_master
import mg_connection
import mg_zone

LOGIN_CTS           = "LOGIN_CTS"
LOGIN_STC           = "LOGIN_STC"
ROOMCHOOSE_CTS      = "ROOMCHOOSE_CTS"
ROOMCHOOSE_STC      = "ROOMCHOOSE_STC"
BATTLE_WORD_CTS     = "BATTLE_WORD_CTS"
BATTLE_XY_CTS       = "BATTLE_XY_CTS"
BATTLE_XY_STC       = "BATTLE_XY_STC"
BATTLE_RESULT_CTS   = "BATTLE_RESULT_CTS"
BATTLE_RESULT_STC   = "BATTLE_RESULT_STC"
GAMEOVER_CTS        = "GAMEOVER_CTS"
GAMEOVER_STC		= "GAMEOVER_STC"

MESSAGETYPE = {	LOGIN_CTS			:"0x00",
				LOGIN_STC			:"0x01",
				ROOMCHOOSE_CTS      :"0x02",
				ROOMCHOOSE_STC      :"0x03",
				BATTLE_WORD_CTS     :"0x04",
				BATTLE_XY_CTS		:"0x05",
				BATTLE_XY_STC		:"0x06",
				BATTLE_RESULT_CTS   :"0x07",
				BATTLE_RESULT_STC	:"0x08",
				GAMEOVER_CTS		:"0x09",
				GAMEOVER_STC		:"0x10"
				}


def getThePrefectObject(xml,socket,userid):
	xmldoc = minidom.parseString(xml).getElementsByTagName("data")
	type = xmldoc[0].attributes["type"].value

	#用户登录验证,如果验证通过，返房间最新信息，否则返回失败信息
	if type ==  MESSAGETYPE[LOGIN_CTS]:
		undata =  unescape_login_CTS(xml,type)
		if	mg_master.vertifyUser(undata,socket):
			return escape_login_STC(mg_master.getAllUsersByRoomId()),None
		else:
			return escape_login_STC(None),None

	#用户选择房间,如果发生异常，是表示房间人数满足，通知房间内全部人数开始战斗 
	if type == MESSAGETYPE[ROOMCHOOSE_CTS]:
		undata,datas= unescape_roomChoose_CTS(xml,type,userid)
		result,allbattle  = escape_roomChoose_STC(undata,datas)
		return result,allbattle

	#战斗双方发送聊天消息，服务器无判断
	if type == MESSAGETYPE[BATTLE_WORD_CTS]:
		return xml,"fullarmy"

	#战斗双方发送战斗消息，服务器无判断
	if type == MESSAGETYPE[BATTLE_XY_CTS]:
		return xml,"fullarmy"

	#战斗结果判定
#	import rpdb2; rpdb2.start_embedded_debugger("melissa")
	if type == MESSAGETYPE[BATTLE_RESULT_CTS]:
		undata = unescape_battleResult_CTS(xml,type,userid)
		if undata:
			return escape_battleResult_STC(undata),"fullarmy"
		else:
			return False,None

	#用户退出判定
	if  type == MESSAGETYPE[GAMEOVER_CTS]:
		undata = unescape_gameOver_CTS(xml,type,userid)
		if undata:
			return escape_gameOver_STC(),None;
			
class user():
	def __init__(self):
		self.id = None
		self.username = None
		self.password = None
		self.type = None
		self.roomid= None
		self.islive = True
		self.army = None
		self.health = 100 

	def getUserName(self):
		return self.username

	def getPassWord(self):
		return self.password

	def getType(self):
		return self.type

	def getRoomId(self):
		return self.roomid

	def getIsLive(self):
		return self.islive

	def getArmy(self):
		return self.army

	def getId(self):
		return self.id

	def getHealth(self):
		return self.health

	def setUserName(self,_username):
		self.username = _username
	
	def setPassWord(self,_password):
		self.password = _password
	
	def setType(self,_type):
		self.type = _type

	def setRoomId(self,_id):
		self.roomid = _id

	def setIsLive(self,_islive):
		self.islive = _islive

	def setId(self,_id):
		self.id = _id

	def setArmy(self,_army):
		self.army = _army
	
	def setHealth(self,_health):
		self.health = _health

	def reset(self):
		self.roomid = None
		self.health = 100


#	<data type="0x00">
#		<user usrname="###" password="###"/>
#	</data> 
def unescape_login_CTS(xml,type):
	u = user()
	xmldoc = minidom.parseString(xml).getElementsByTagName("user")
	u.setUserName(xmldoc[0].attributes["usrname"].value)
	u.setPassWord(xmldoc[0].attributes["password"].value)
	u.setType(type)
	return u


#返回第一页的用户详细信息
#	faile
#	<data type="0x01">
#		<vertification value="0">
#	</data>

#	success
#	<data type="0x01">
#		<vertification value="1">
#	</data>
#	success

def escape_login_STC(object):
	if object is  None:
		return "<data type='0x01'><vertification value='0/>'</data>"
	else:
		prefix = "<data type='0x01'><vertification value='1'/>"
		endfix = "</data>"
		rooms = ""

		for data in object:
			v = data
			if v[0].getRoomId() is not None:
				rooms = "<room id='"+str(v[0].getRoomId())+"'>"
				for user in v:
					rooms  = rooms + "<user username='"+str(user.getUserName())+"'/>"
				rooms = rooms+"</room>"
		return prefix + rooms + endfix



def unescape_roomChoose_CTS(xml,type,userid):
	xmldoc = minidom.parseString(xml).getElementsByTagName("choosedroom")
	roomid = str(xmldoc[0].attributes["id"].value)
	result,data = mg_zone.addUserToRoom(roomid,userid)
	if result != None:
		print "<-- Client request to choose room -->"	
		return result,data

def escape_roomChoose_STC(army,datas):
	if army != "fullarmy":
		return "<data type='0x03'><startbattle value='"+str(army)+"'/></data>",None
	else:
	#	return "<data type='0x03'><startbattle value='start'/></data>","fullarmy"
		prefix = "<data type='0x03'>"
		endfix = "</data>"
		rooms = ""
		if datas[0].getRoomId() !=  None:
			rooms = "<room id='"+str(datas[0].getRoomId())+"'>"
			for user in datas:
				rooms  = rooms + "<user id='"+str(user.getId())+"' army='"+str(user.getArmy())+"' username='"+str(user.getUserName())+"'/>"
			rooms = rooms+"</room>"
		return prefix + rooms + endfix,"fullarmy"

def unescape_battleResult_CTS(xml,type,userid):
	xmldoc = minidom.parseString(xml).getElementsByTagName("user")
	users = []
	for user in xmldoc:
		userhealth = {"id":user.attributes["id"].value,"health":user.attributes["health"].value}
		users.append(userhealth)
	result = mg_zone.makeJudge(users) 
	return result

def escape_battleResult_STC(undata):
	pre = "<data type='0x08'>"
	data = ""
	for user in undata:
		data = data + "<user id ='"+str(user.getId())+"' "+"health='"+str(user.getHealth())+"'/>"
	end = "</data>"

	return pre + data + end

def	 unescape_gameOver_CTS(xml,type,userid):
	xmldoc = minidom.parseString(xml).getElementsByTagName("choice")
	choice = xmldoc[0].attributes["v"].value
	if choice == "quit":
		mg_master.cache.resetUser(userid)
	return True


def escape_gameOver_STC():
	m = "<data type='0x10'><reset v='success'></data>"
	return m








